package com.tutorial.boot.demo.service;

import com.tutorial.boot.demo.converter.StudentConverter;
import com.tutorial.boot.demo.dao.Student;
import com.tutorial.boot.demo.dao.StudentRepository;
import com.tutorial.boot.demo.dto.StudentDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class StudentServiceImpl implements StudentService{

    @Autowired
    private StudentRepository studentRepository;



    @Override
    public StudentDTO getStudentById(long id) {
        // what is runtimeException
        Student student = studentRepository.findById(id).orElseThrow(RuntimeException::new);
        return StudentConverter.convertStudent(student);
    }

    @Override
    public Long addNewStudent(StudentDTO studentDTO) {
        // 先判断邮箱存不存在
        List<Student> studentList = studentRepository.findByEmail(studentDTO.getEmail());
        if(!CollectionUtils.isEmpty(studentList)){
            throw new IllegalStateException("email:" + studentDTO.getEmail() + "has been taken");
        }
        Student student = studentRepository.save(StudentConverter.convertStudentDTO(studentDTO));
        return student.getId();
    }

    @Override
    public void deleteStudentById(long id) {
        // 先判断id存不存在
        studentRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("id: " + id + " doesn't exist!!"));
        studentRepository.deleteById(id);


    }

    @Override
    @Transactional
    public StudentDTO updateStudentById(long id, String name, String email) {
        Student studentInDB = studentRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("id: " + id + " doesn't exist!!"));

        // 如果传进来有名字并且和库里的不一样就改
        if(StringUtils.hasLength(name) && !studentInDB.getName().equals(name)){
            studentInDB.setName(name);
        }

        // 如果传进来有邮箱并且和库里的不一样就改
        if(StringUtils.hasLength(email) && !studentInDB.getEmail().equals(email)){
            studentInDB.setEmail(email);
        }

        // 把新的student存进去
        Student student = studentRepository.save(studentInDB);
        return StudentConverter.convertStudent(student);
    }

    @Override
    public List<StudentDTO> getAllStudents() {
        List<Student> students = studentRepository.findAll();
        return students.stream()
                .map(StudentConverter::convertStudent)
                .collect(Collectors.toList());

    }
}
